package com.yzs.core.utils

import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
 * author : yzs
 * time   : 2021/08/09
 * desc   : Gson 工具
 */
val gson by lazy { GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create() }

fun toJson(obj: Any?) = gson.toJson(obj) ?: ""

fun toMap(json: String?): Map<*, *>? {
    return try {
        gson.fromJson<Map<*, *>>(json, MutableMap::class.java)
    } catch (e: Exception) {
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}

fun <T> fromJson(json: String?, type: Type?): T {
    return try {
//        //借助TypeToken类获取具体的泛型类型
//        val type = object : TypeToken<T>() {}.type
        gson.fromJson(json, type)
    } catch (e: Exception) {
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}


fun <T> fromJson(json: JsonElement?, type: Type): T {
    return try {
//        //借助TypeToken类获取具体的泛型类型
//        val type = object : TypeToken<T>() {}.type
        gson.fromJson(json, type)
    } catch (e: Exception) {
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}

fun <T> fromJsonList(json: JsonElement?, type: Type): MutableList<T> {
    return try {
        gson.fromJson(json, type(type))
    }catch (e:Exception){
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}

fun <T> fromJsonList(json: String?, type: Type): MutableList<T> {
    return try {
        gson.fromJson(json, type(type))
    }catch (e:Exception){
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}

private fun type(vararg types: Type): ParameterizedType {
    return object : ParameterizedType {
        override fun getRawType(): Type {
            return MutableList::class.java
        }

        override fun getOwnerType(): Type? {
            return null
        }

        override fun getActualTypeArguments(): Array<out Type> {
            return types
        }
    }
}

inline fun <reified T> fromJsonToListModel(json: JsonElement?):T{
    return try {
        //借助TypeToken类获取具体的泛型类型
        val type = object : TypeToken<T>() {}.type
        gson.fromJson(json, type)
    } catch (e: Exception) {
        e.printStackTrace()
        throw ClassCastException("数据转换异常")
    }
}